package com.lindroy.androidplayer.ui.adapter

import android.view.LayoutInflater
import android.view.ViewGroup
import androidx.databinding.DataBindingUtil
import androidx.lifecycle.LifecycleOwner
import androidx.recyclerview.widget.RecyclerView
import com.lindroy.androidplayer.R
import com.lindroy.androidplayer.databinding.LayoutBannerBinding
import com.lindroy.androidplayer.viewmodels.BannerViewModel

/**
 * @author Lin
 * @date 2022/1/18
 * @function
 */
class BannerTypeAdapter(private val owner: LifecycleOwner) :
    RecyclerView.Adapter<BannerTypeAdapter.ViewHolder>() {

    private val banners = arrayListOf<BannerViewModel>()

    fun setData(bannerList: List<BannerViewModel>) {
        this.banners.clear()
        this.banners.addAll(bannerList)
        notifyDataSetChanged()
    }

    fun clearData(){
        this.banners.clear()
        notifyDataSetChanged()
    }

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int) =
        ViewHolder((DataBindingUtil.inflate(
            LayoutInflater.from(parent.context),
            R.layout.layout_banner,
            parent,
            false
        ) as LayoutBannerBinding).apply {
            lifecycleOwner = owner
        })

    override fun onBindViewHolder(holder: ViewHolder, position: Int) {
        holder.bind.banner.apply {
            setAdapter(BannerAdapter(owner))
            setLifecycleRegistry(owner.lifecycle)
        }.create(banners)
    }

    override fun getItemCount(): Int = if (banners.isNotEmpty()) 1 else 0

    class ViewHolder(val bind: LayoutBannerBinding) : RecyclerView.ViewHolder(bind.root)

}